package com.feige.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.feige.constant.Constants;
import com.feige.utils.http.ServletUtils;
import com.feige.utils.jwt.JwtUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 用于创建插入时间和修改时间
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        String token = ServletUtils.getRequest().getHeader(Constants.TOKEN_KEY);
        String username = JwtUtils.getUsernameAndNumFromToken(token);
        this.setFieldValByName("createBy", username, metaObject);
        this.setFieldValByName("modifyBy", username, metaObject);
        this.setFieldValByName("gmtCreate", new Date(), metaObject);
        this.setFieldValByName("gmtModified", new Date(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String token = ServletUtils.getRequest().getHeader(Constants.TOKEN_KEY);
        String username = JwtUtils.getUsernameAndNumFromToken(token);
        this.setFieldValByName("modifyBy", username, metaObject);
        this.setFieldValByName("gmtModified", new Date(), metaObject);
    }
}
